package com.ruoyi.merchant.service.impl;

import java.io.IOException;
import java.util.*;

import com.alibaba.fastjson2.JSON;
import com.mysql.cj.protocol.Message;
import com.ruoyi.merchant.elasticsearch.PerShopService;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.merchant.utils.GeocodingUtil;
import com.ruoyi.merchant.utils.WebSocketServer;
import com.ruoyi.merchant.utils.list.ReturnLocationBean;
import com.ruoyi.merchant.utils.pojo.MessagePojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.merchant.mapper.RescueTaskMapper;
import com.ruoyi.merchant.domain.RescueTask;
import com.ruoyi.merchant.service.IRescueTaskService;

import static com.ruoyi.merchant.utils.GeocodingUtil.AK;

/**
 * 救援任务管理Service业务层处理
 * 
 * @author ysq
 * @date 2024-09-10
 */
@Service
public class RescueTaskServiceImpl implements IRescueTaskService 
{
    @Autowired
    private RescueTaskMapper rescueTaskMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private PerShopService perShopService;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 查询救援任务管理
     * 
     * @param id 救援任务管理主键
     * @return 救援任务管理
     */
    @Override
    public RescueTask selectRescueTaskById(Long id)
    {
        return rescueTaskMapper.selectRescueTaskById(id);
    }

    /**
     * 查询救援任务管理列表
     * 
     * @param rescueTask 救援任务管理
     * @return 救援任务管理
     */
    @Override
    public List<RescueTask> selectRescueTaskList(RescueTask rescueTask)
    {
        return rescueTaskMapper.selectRescueTaskList(rescueTask);
    }

    /**
     * 新增救援任务管理
     * 
     * @param rescueTask 救援任务管理
     * @return 结果
     */
    @Override
    public int insertRescueTask(RescueTask rescueTask)
    {
        // 获取用户的位置
        String position = rescueTask.getPosition();
        GeocodingUtil geocodingUtil = new GeocodingUtil();
        ReturnLocationBean locationBean = geocodingUtil.addressToLongitude(position);
        double longitude = 0;
        double latitude = 0;
        if (locationBean != null && locationBean.getResult() != null) {
            // 获取经纬度
            ReturnLocationBean.Location location = locationBean.getResult().getLocation();
            if (location != null) {
                longitude = Double.parseDouble(String.format("%.3f", location.getLng()));// 经度
                latitude = Double.parseDouble(String.format("%.3f", location.getLat()));// 纬度
                // 打印经纬度
                System.out.println("Longitude: " + longitude + ", Latitude: " + latitude);
            } else {
                System.out.println("获取经纬度失败: location为空");
                return -1; // 或者处理失败情况
            }
        } else {
            System.out.println("获取经纬度失败: locationBean为空或result为空");
            return -1; // 或者处理失败情况
        }
        System.out.println("Longitude: " + longitude + ", Latitude: " + latitude);
        //1.前端定位到用户的位置，根据用户的位置从Redis中获取附近50km内的店铺
        List<String> nearbyShops = redisService.getNearbyShops(longitude, latitude, 50000);
        if (nearbyShops.isEmpty()) {
            System.out.println("在指定半径内未找到店铺.");
        } else {
            System.out.println("在指定半径内找到的店铺ID: " + nearbyShops);
        }
        //2.查找到的店铺，通过elasticsearch全文检索通过type聚合，展示出具有修车功能的店铺
        List<String> ids = perShopService.performAggregation();
        System.out.println("ids:"+ids);
        ids.forEach(id -> {
            String shopId = String.valueOf(id);
            System.out.println("shopId: " + shopId);
        });
        //对比Redis和elasticsearch中店铺的id，找到匹配的店铺
        List<String> shopIds = new ArrayList<>();
        for (String id : nearbyShops) {
            if (ids.contains(id)) {
                shopIds.add(id);
            }
            System.out.println("shopIds: " + shopIds);
        }
        String id = null;
        for (String shopId : shopIds) {
            id = shopId;
        }
        System.out.println("id: " + id);
        int i = rescueTaskMapper.insertRescueTask(rescueTask);
        Long id1 = rescueTask.getId();
        MessagePojo messagePojo = new MessagePojo();
        messagePojo.setId(id1);
        messagePojo.setUid(rescueTask.getUid());
        messagePojo.setName(rescueTask.getName());
        messagePojo.setPhone(rescueTask.getPhone());
        messagePojo.setStatus(rescueTask.getStatus());
        // 将对象转换为 JSON 字符串
        String s = JSON.toJSONString(messagePojo);
        System.out.println("JSON: " + s);

        System.out.println("id1: " + id1);
        //3.通过websocket通知商家
        try {
            webSocketServer.sendInfo(s, String.valueOf(id));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return i;
    }

    /**
     * 修改救援任务管理
     * 
     * @param rescueTask 救援任务管理
     * @return 结果
     */
    @Override
    public int updateRescueTask(RescueTask rescueTask)
    {
        System.out.println("RescueTask: " + rescueTask);
        MessagePojo messagePojo = new MessagePojo();
        Long id1 = rescueTask.getId();
        Long id = rescueTask.getUid();
        System.out.println("id: " + id);
        messagePojo.setId(id1);
        messagePojo.setUid(rescueTask.getMid());
        messagePojo.setName(rescueTask.getName());
        messagePojo.setPhone(rescueTask.getPhone());
        messagePojo.setStatus(rescueTask.getStatus());
        String s = JSON.toJSONString(messagePojo);
        //4.商家接单后通过websocket通知用户
        try {
            webSocketServer.sendInfo(s, String.valueOf(7));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return rescueTaskMapper.updateRescueTask(rescueTask);
    }

    /**
     * 批量删除救援任务管理
     * 
     * @param ids 需要删除的救援任务管理主键
     * @return 结果
     */
    @Override
    public int deleteRescueTaskByIds(Long[] ids)
    {
        return rescueTaskMapper.deleteRescueTaskByIds(ids);
    }

    /**
     * 删除救援任务管理信息
     * 
     * @param id 救援任务管理主键
     * @return 结果
     */
    @Override
    public int deleteRescueTaskById(Long id)
    {
        return rescueTaskMapper.deleteRescueTaskById(id);
    }

    @Override
    public List<RescueTask> selectStatusAndMid(Long mid) {
        return rescueTaskMapper.selectStatusAndMid(mid);
    }
}
